package org.myspringframework.mvc.processor.impl;

import org.myspringframework.mvc.RequestProcessorChain;
import org.myspringframework.mvc.processor.RequestProcessor;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * org.myspringframework.mvc.processor.impl<br>
 * jsp请求资源处理
 *
 * @author jaymin
 * @since 2021/5/22
 */
public class JspRequestProcessor implements RequestProcessor {
    /**
     * jsp请求的RequestDispatcher的名称
     */
    private static final String JSP_SERVLET = "jsp";
    /**
     * jsp请求资源路径前缀
     */
    private static final String JSP_RESOURCE_PREFIX = "/templates/";
    /**
     * jsp的RequestDispatcher,处理jsp资源
     */
    private RequestDispatcher jspServlet;

    public JspRequestProcessor(ServletContext servletContext) {
        jspServlet = servletContext.getNamedDispatcher(JSP_SERVLET);
        if (Objects.isNull(jspServlet)) {
            throw new RuntimeException("there is no jsp servlet");
        }
    }

    @Override
    public boolean proceed(RequestProcessorChain requestProcessorChain) throws Exception {
        String requestPath = requestProcessorChain.getRequestPath();
        HttpServletRequest httpServletRequest = requestProcessorChain.getHttpServletRequest();
        HttpServletResponse httpServletResponse = requestProcessorChain.getHttpServletResponse();
        if (isJspResource(requestPath)) {
            jspServlet.forward(httpServletRequest, httpServletResponse);
            return false;
        }
        return true;
    }

    /**
     * 是否请求的是jsp资源
     * @param requestPath
     * @return
     */
    private boolean isJspResource(String requestPath) {
        return requestPath.startsWith(JSP_RESOURCE_PREFIX);
    }
}
